# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import datetime
import math
import webapp2


def human_delta(delta):
    value = 0
    label = u'algum tempo'
    if delta.total_seconds() == 0:
        value = 0.1
        label = u'segundos'
    elif delta.days > 0:
        if delta.days < 7:
            value = delta.days
            if value == 1:
                label = u'dia'
            else:
                label = u'dias'
        elif delta.days < 28:
            value = int(math.floor(delta.days / 7))
            if value == 1:
                label = u'semana'
            else:
                label = u'semanas'
        else:
            value = 1
            label = u'mês ou mais'
    elif delta.seconds < 60:
        value = delta.seconds
        if value == 1:
            label = u'segundo'
        else:
            label = u'segundos'
    elif delta.seconds < 3600:
        value = int(math.floor(delta.seconds / 60))
        if value == 1:
            label = u'minuto'
        else:
            label = u'minutos'
    else:
        value = int(math.floor(delta.seconds / 3600))
        if value == 1:
            label = u'hora'
        else:
            label = u'horas'
    return (value, label)


def human_delta_now(past):
    delta = datetime.datetime.utcnow() - past
    return human_delta(delta)


config = {
    'webapp2_extras.sessions': {
        'secret_key': 'notUsocsecretiaszyouRcouldTthink',
        'cookie_name': 'WGSESSION',
    },
    'wowgae.short': {
        'domain': 'cenar.us',
    },
    'wowgae.ranks': {
        'admin': 1,
        'officer': 2,
    },
}


from webapp2_extras import routes
from wowgae.activation import ActivationHandler
from wowgae.activation import ActivationTask
from wowgae.activation import SetMainHandler
from wowgae.wiki import WikiHandler
from wowgae.cron import HourlyJob, DailyJob, GuildUpdatingTask, \
    UpdateAccountMembershipTask, WeeklyJob
from wowgae.report import LatestPagesHandler, ReportsHandler, \
    LatestAccountsHandler, MissingActivationHandler, \
    PendingActivationHandler, LowsMissingActivationHandler
from wowgae.short import CustomizeShortURLHandler, CreateShortURLHandler, \
    ShortURLHandler


route_enus = {
    'shortener-create': r'/shortener/create',
    'admin-shortener': r'/admin/shortener/custom',
    'activation-finished': r'/activation/finished',
    'activation-pending': r'/activation/pending',
    'activation-set_main': r'/activation/set-main/<name>',
    'activation': r'/activation',
    'wiki-diff': r'/wiki/<page>/diff/<reva:\d{1,4}>-<revb:\d{1,4}>',
    'wiki-revision': r'/wiki/<page>/revision/<revision:\d{1,4}>',
    'wiki-edit': r'/wiki/<page>/edit',
    'wiki-history': r'/wiki/<page>/history',
    'wiki': r'/wiki/<page>',
    'wiki-home': r'/wiki',
    'reports-pending_activation': r'/reports/pending-activation',
    'reports-lows_missing_activation': r'/reports/lows-missing-activation',
    'reports-missing_activation': r'/reports/missing-activation',
    'reports-latest_accounts': r'/reports/latest-accounts',
    'reports-latest_pages': r'/reports/latest-pages',
    'reports': r'/reports',
    'home': r'/',
}


route_ptbr = {
    'shortener-create': r'/encurtador/criar',
    'admin-shortener-custom': r'/admin/encurtador/personalizado',
    'activation-finished': r'/ativacao/concluida',
    'activation-pending': r'/ativacao/pendente',
    'activation-set_main': r'/ativacao/define-principal/<name>',
    'activation': r'/ativacao',
    'wiki-diff': r'/wiki/<page>/diff/<reva:\d{1,4}>-<revb:\d{1,4}>',
    'wiki-revision': r'/wiki/<page>/revisao/<revision:\d{1,4}>',
    'wiki-edit': r'/wiki/<page>/editar',
    'wiki-history': r'/wiki/<page>/historico',
    'wiki': ur'/wiki/<page>',
    'wiki-home': r'/wiki',
    'reports-pending_activation': r'/relatorios/ativacao-pendente',
    'reports-lows_missing_activation': r'/relatorios/baixos-faltando-ativacao',
    'reports-missing_activation': r'/relatorios/faltando-ativacao',
    'reports-latest_accounts': r'/relatorios/ultimas-contas',
    'reports-latest_pages': r'/relatorios/ultimas-paginas',
    'reports': r'/relatorios',
    'home': r'/',
}


route_path = route_ptbr


routes = [

    routes.DomainRoute(r'<:.*>cenar.us<:.*>', [
        webapp2.Route(r'/<code>', handler=ShortURLHandler),
        routes.RedirectRoute(r'/', redirect_to=lambda handler, *args, **kwargs:
                webapp2.uri_for('shortener-create',
                                _netloc='www.discipulosdecenarius.com')
            ),
    ]),

    routes.DomainRoute(r'<:.*(discipulosdecenarius\.com)|(localhost)>', [

        webapp2.Route(route_path['shortener-create'],
                      handler=CreateShortURLHandler,
                      name='shortener-create'),

        webapp2.Route(route_path['activation-finished'],
                      handler=ActivationHandler,
                      handler_method='get_finished',
                      methods=['GET'],
                      name='activation-finished'),

        webapp2.Route(route_path['activation-pending'],
                      handler=ActivationHandler,
                      handler_method='get_pending',
                      methods=['GET'],
                      name='activation-pending'),

        webapp2.Route(route_path['activation-set_main'],
                      handler=SetMainHandler,
                      name='activation-set_main'),

        webapp2.Route(route_path['activation'],
                      handler=ActivationHandler,
                      name='activation'),

        webapp2.Route(route_path['wiki-diff'],
                      handler=WikiHandler,
                      handler_method='get_diff',
                      methods=['GET'],
                      name='wiki-diff'),

        webapp2.Route(route_path['wiki-revision'],
                      handler=WikiHandler,
                      handler_method='get_revision',
                      methods=['GET'],
                      name='wiki-revision'),

        webapp2.Route(route_path['wiki-edit'],
                      handler=WikiHandler,
                      handler_method='get_edit',
                      methods=['GET'],
                      name='wiki-edit'),

        webapp2.Route(route_path['wiki-history'],
                      handler=WikiHandler,
                      handler_method='get_history',
                      methods=['GET'],
                      name='wiki-history'),

        webapp2.Route(route_path['wiki'],
                      handler=WikiHandler,
                      name='wiki'),

        webapp2.Route(route_path['wiki-home'],
                      handler=WikiHandler,
                      handler_method='get_home',
                      methods=['GET'],
                      name='wiki-home'),

        webapp2.Route(route_path['reports-pending_activation'],
                      handler=PendingActivationHandler,
                      name='reports-pending_activation'),

        webapp2.Route(route_path['reports-missing_activation'],
                      handler=MissingActivationHandler,
                      name='reports-missing_activation'),

        webapp2.Route(route_path['reports-lows_missing_activation'],
                      handler=LowsMissingActivationHandler,
                      name='reports-lows_missing_activation'),

        webapp2.Route(route_path['reports-latest_pages'],
                      handler=LatestPagesHandler,
                      name='reports-latest_pages'),

        webapp2.Route(route_path['reports-latest_accounts'],
                      handler=LatestAccountsHandler,
                      name='reports-latest_accounts'),

        webapp2.Route(route_path['reports'],
                      handler=ReportsHandler,
                      name='reports'),

        webapp2.Route(route_path['admin-shortener-custom'],
                      handler=CustomizeShortURLHandler,
                      name='admin-shortener-custom'),

        webapp2.Route(route_path['home'],
                      handler=WikiHandler,
                      handler_method='get_home',
                      methods=['GET'],
                      name='home'),
    ]),
]


task_routes = [

    webapp2.Route(r'/task/activations',
                  handler=ActivationTask,
                  name='activations'),

    webapp2.Route(r'/task/guildupdating',
                  handler=GuildUpdatingTask,
                  name='guildupdating'),

    webapp2.Route(r'/task/updateaccountmembership',
                  handler=UpdateAccountMembershipTask,
                  name='updateaccountmembership'),

]


job_routes = [

    webapp2.Route(r'/job/hourly',
                  handler=HourlyJob,
                  name='hourly'),

    webapp2.Route(r'/job/daily',
                  handler=DailyJob,
                  name='daily'),

    webapp2.Route(r'/job/weekly',
                  handler=WeeklyJob,
                  name='weekly'),

]


app = webapp2.WSGIApplication(routes, config=config, debug=True)

task = webapp2.WSGIApplication(task_routes, config=config, debug=True)

job = webapp2.WSGIApplication(job_routes, config=config, debug=True)
